package com.vjwealth.android.nos.service

import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import com.vjwealth.android.nos.R

/**
 * projectName KNOS
 * date 2017/9/28
 * description com.vjwealth.android.nos.service
 */
class MusicService : Service(), MediaPlayer.OnCompletionListener {

    override fun onCompletion(mp: MediaPlayer?) {
        stopSelf()
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }

    //为了和Activity交互，我们需要定义一个Binder对象
    internal inner class MusicBinder : Binder() {

        //返回Service对象
        val service: MusicService
            get() = this@MusicService
    }

    private val binder = MusicBinder()
    internal var player: MediaPlayer? = null

    override fun onCreate() {
        super.onCreate()
        player = MediaPlayer.create(getApplicationContext(), R.raw.start)
        player!!.setOnCompletionListener(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if(!player!!.isPlaying){
            player!!.start()
        }
        return START_STICKY
    }

    override fun onDestroy() {
        if(player!!.isPlaying){
            player!!.stop()
        }
        player!!.release()
    }
}